﻿namespace Amazon.Checkout.Controllers
{
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Helpers;
    using Models;
    using Orchard.Localization;
    using Orchard.Themes;
    using Orchard.UI.Admin;
    using Services;

    [Admin]
    [Themed]
    public class TaxRuleController : Controller
    {
        private readonly ICheckoutByAmazonService amazonService;
        private readonly Localizer T;

        public TaxRuleController(ICheckoutByAmazonService amazonService)
        {
            this.amazonService = amazonService;
            this.T = NullLocalizer.Instance;
        }

        [HttpGet]
        public JsonResult List(int taxTableId)
        {
            return this.Json(this.amazonService.GetTaxRules(taxTableId) ?? new List<TaxRuleRecord>());
        }

        [HttpGet]
        public void Delete(int taxRuleId)
        {
            this.amazonService.DeleteTaxRule(taxRuleId);
        }

        [HttpPost]
        public JsonResult New(string regionType, string region, decimal rate, bool shippingTaxed)
        {
            if (rate <= 0 || rate > AmazonCheckout.TaxTable.MaximumTaxRate)
            {
                return this.Json(new { error = this.T("The tax rate {0} is out of range. It should be greater than {1} and less than or equal to {2}.", rate, AmazonCheckout.TaxTable.MinimumTaxRate, AmazonCheckout.TaxTable.MaximumTaxRate) });
            }

            var taxRule = this.amazonService.CreateTaxRule(regionType, region, rate, shippingTaxed);
            return this.Json(taxRule);
        }
    }
}